package com.yuan.mqtt.client;

import org.eclipse.paho.client.mqttv3.*;

/**
 * @Classname PushCallback
 * @Description :
 * @Date 2021/9/14 15:38
 * @Author cfy
 */

public class PushCallback implements MqttCallback {

    private MqttClient client;
    private MqttConnectOptions options;
    private String[] topic;
    private int[] qos;

    public PushCallback() {
    }

    public PushCallback(MqttClient client, MqttConnectOptions options, String[] topic, int[] qos) {
        this.client = client;
        this.options = options;
        this.topic = topic;
        this.qos = qos;
    }

    /**
     * 断开重连
     */
    @Override
    public void connectionLost(Throwable cause) {
        while (true) {
            try {
                Thread.sleep(30000);
                client.connect(options);
                //订阅消息
                client.subscribe(topic, qos);
                break;
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }

    }


    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

        System.out.println("接收消息主题 : " + topic);
        System.out.println("接收消息Qos : " + message.getQos());
        System.out.println("接收消息内容 : " + new String(message.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }
}
